﻿/**
 * Dichan.com -- Global.JS
 * 
 * Author:         TERRY.L <yao618@163.com>
 * Version:        1.1.0
 * Create Date:    2009/12/15
 * Update Details: 
 * 2009/12/15	Create
 * 2009/12/16	Add ajaxPro method
 * 2009/12/20	Add jAjaxProMethod property
 * 2009/12/30	Add ClassX Object
 * 2009/12/31	Modify Global prototype Class
 * Based on jQuery library & ajaxpro2
 * 
*/


/**
 * 声明Bool值，兼容服务器端Bool值
 */
var True = true, False = false;

/**
 * Global类定义
 * @param {Object} debugparam URL调试参数名
 * @param {Object} ajaxmethod JAjaxPro的Post请求Header的参数名
 */
function Global(debugparam, ajaxmethod){
	/**
	 * URL调试参数名
	 */
	this.debugParam = debugparam || "jsdebug";
	/**
	 * 是否调试模式
	 */
	this.debug = false;
	/**
	 * 【暂未启用】
	 * JAjaxPro的Post请求Header的参数名
	 */
	this.jAjaxProMethod = ajaxmethod || "X-JAjaxPro-Method";
	/**
	 * 页面作用域对象
	 */
	this.Page = {};
	var me = this;

	/**
	 * 根据页面URL判断是否进入调试状态
	 */
	(function() {
	    var debug = me.getQueryString(me.debugParam);
	    if (debug != null && debug == true) {
	        me.debug = true;
	    }
	})();
	/**
	 * 处理IE6下默认不缓存背景图片
	 */
	(function() {
	    var ua = window.navigator.userAgent.toLowerCase();
	    var isOpera = ua.indexOf("opera") > -1;
	    var isIE = !isOpera && ua.indexOf("msie") > -1;
	    var isIE7 = !isOpera && ua.indexOf("msie 7") > -1;
	
	    if (isIE && !isIE7) {
	        try {
	            document.execCommand("BackgroundImageCache", false, true);
	        } catch (e) { }
	    }
	})();
}

/**
 * 显示调试信息（浏览器FireFox/IE，显示至控制台）
 * @param {Object|String} info 需要显示的对象/字符串
 */
Global.prototype.log = function(info) {
    var isObject = (typeof info == "object");
    if (typeof console != "undefined" && typeof console.info != "undefined") {
        console.info("Global Debug: " + (isObject ? "%o" : "%s"), info);
    } else {
        window.alert((isObject ? "ERROR in Server Side! " : "") + info);
    }
};

/**
 * 获取URL参数值
 * @param {String} key URL中的参数名
 * @return null/对应的参数值
 */
Global.prototype.getQueryString = function(key) {
	var str = decodeURI(window.location.search);
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
    var r = str.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    } else {
        return null;
    }
};

/**
 * 全角字符转为半角字符
 * @param {String} str 包含全角字符的字符串
 * @return 格式化为半角的字符串
 */
Global.prototype.FullToHalfChar = function(str) {
    var myArray = [];
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt != null && String.fromCharCode != null) {
            var charCode = str.charCodeAt(i);
            if (charCode > 0xfee0) {
                myArray[i] = String.fromCharCode(charCode - 0xfee0);
            }
            else
                myArray[i] = String.fromCharCode(charCode);
        }
    }
    return myArray.join('');  
}

/**
 * 【暂未启用】
 * AjaxPro方式访问服务器端方法
 * @param {String} url ajaxpro自动生成的url
 * @param {String} method server端方法名
 * @param {Object} paramjson json格式的参数
 * @param {String} callback client回调函数名 
 */
Global.prototype.ajaxPro = function(url, method, paramjson, callback) {
    if (typeof jQuery == "undefined" || typeof JSON == "undefined") {
        this.log("jQuery library and JSON2.js are required");
        return;
    }
	var me = this;

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(paramjson),
        beforeSend: function(xhr) {
            xhr.setRequestHeader(me.jAjaxProMethod, method);
        },
        success: function(s) {
            var r = {};
            eval("s = " + s + "*" + "/");
            if (s != null) {
                callback.call(window, s);
            } else {
                me.log(r.error.Message);
            }
        },
        error: function(s) {
            me.log(s);
        }
    });
};

/**
 * 设置cookies
 * @param {String} name cookie键
 * @param {String} value cookie值
 */
Global.prototype.setCookie = function(name, value) {
    var argv = setCookie.arguments;
    var argc = setCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    if (expires != null) {
        var LargeExpDate = new Date();
        LargeExpDate.setTime(LargeExpDate.getTime() + (expires * 1000 * 3600 * 24));
    }
    document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + LargeExpDate.toGMTString()));
};

/**
 * 获取对应值
 * @param {String} name cookie键
 * @return cookie值
 */
Global.prototype.getCookie = function(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) {
        return unescape(arr[2]);
    } else {
        return null;
    }
};

/**
 * flash调用
 * @param {String} url flash地址
 * @param {String} width flash宽度
 * @param {String} height flash高度
 * @param {String} id flash控件ID
 */
Global.prototype.writeFlash = function(url, width, height, id) {
    document.write('<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000" id="obj1" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" border="0" width="' + width + '" height="' + height + '">');
    document.write('<param name="movie" value="' + url + '">');
    document.write('<param name="quality" value="high"> ');
    document.write('<param name="wmode" value="transparent"> ');
    document.write('<param name="menu" value="false"> ');
    document.write('<embed src="' + url + '" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + width + '" height="' + height + '" quality="High" wmode="transparent">');
    document.write('</embed>');
    document.write('</object>');
};

/**
 * 检查标签匹配闭合
 * @param string tagname 表单元素name
 * @return 1,0, 1表示闭合良好
 * 
 * @yongbin 080828, 加入注释检测。修订原检测方式。
*/
Global.prototype.checkHTMLTag = function(content, noAlert) {
    var retag = content;

    function compare(txt1, txt2) {
        var txt = '<' + '/' + txt1.substr(1);
        return (txt == txt2) ? 1 : 0;
    }
    function checkComment(txt) {
        var _ret;
        txt = txt.replace(/\r|\n/ig, '');
        txt = txt.replace(/<style *[^<>]*>.*?<\/style>/ig, '');
        txt = txt.replace(/<script *[^<>]*>.*?<\/script>/ig, '');
        if (/<\!-+>/ig.test(txt) || /<\!--(-+(.*?)|(.*?)-+)-->/ig.test(txt)) {
            _ret = false;
        }
        else {
            if (txt.split("<!--").length != txt.split("-->").length)
                _ret = false;
            else {
                _ret = true;
            }
        }
        return _ret;
    }

    if (retag == '') {
        return 1; //空串直接返回1
    }

    // pass comment tag checker?
    if (checkComment(retag) == false) {
        if (!noAlert)
            alert("注释代码错误，请遵守<!-- comment -->格式！\n提示：<!--->, <!----->, <!--- comment -->等等都是不规范的注释。");
        return 0;
    }
    else {
        retag = retag.replace(/\r|\n/ig, ''); //除去回车和换行	
        // 去掉不能很好控制的<script>...<\/script>和<!--...-->
        retag = retag.replace(/<style *[^<>]*>.*?<\/style>/ig, '');
        retag = retag.replace(/<script *[^<>]*>.*?<\/script>/ig, '');
        retag = retag.replace(/<\!--.*?-->/ig, '');

        var arrIntElement = retag.match(/<\/?[A-Za-z][a-z0-9]*[^>]*>/ig);

        if (arrIntElement != null) {


            //预处理标签,得到规整的标签数组,去掉所有属性只留下<a>和</a>
            var arrPrElement = Array();
            for (var k = 0; k < arrIntElement.length; k++) {
                arrPrElement[k] = arrIntElement[k].replace(/(<\/?[A-Za-z0-9]+) *[^>]*>/ig, "$1>");
                arrPrElement[k] = arrPrElement[k].replace(/[\s]+/g, '').toLowerCase();
            }

            //不需要配对的标签,小写
            var arrMinus = new Array('<img>', '<input>', '<meta>', '<hr>', '<br>', '<link>', '<param>', '<frame>', '<base>', '<basefont>', '<isindex>', '<area>');

            //去掉多余的单标签标记,返回新的arrIntElement
            for (var i = 0; i < arrPrElement.length; i++) {
                for (var k = 0; k < arrMinus.length; k++) {
                    if (arrPrElement[i] == arrMinus[k]) {
                        arrPrElement.splice(i, 1);
                        i--;
                    }
                }
            }

            //判断<aaa>与</aaa>是配对的html标签
            var stack = new Array();
            stack[0] = '#';
            var p = 0;
            var problem;
            for (var j = 0; j < arrPrElement.length; j++) {
                if (compare(stack[p], arrPrElement[j])) {
                    p--;
                    stack.length--;
                }
                else {
                    stack[++p] = arrPrElement[j];
                }
            }

            if (stack[p] != "#") {
                if (!noAlert)
                    alert("存在未闭合的html标签，请检查<a>,<div>,<p>,<li>,<ul>,<font>等标签是否闭合");
                return 0;
            }

            //双引号和单引号完整性检查
            for (var k = 0; k < arrIntElement.length; k++) {
                var rr = arrIntElement[k].match(/\"/ig);
                var r = arrIntElement[k].match(/\'/ig);
                if (rr != null) {
                    if (rr.length % 2 != 0) {
                        if (!noAlert)
                            alert("警告：" + arrIntElement[k] + " 双引号不完整");
                        return 0;
                    }
                }
                if (r != null) {
                    if (r.length % 2 != 0) {
                        if (!noAlert)
                            alert("警告：" + arrIntElement[k] + " 单引号不完整");
                        return 0;
                    }
                }
            }
        }
    }

    return 1;
};

/**
 * 复制内容至剪切板
 * @param {String} txt 复制的内容 
 */
Global.prototype.copyToClipboard = function(txt) {
    if (window.clipboardData) {
        window.clipboardData.clearData();
        window.clipboardData.setData("Text", txt);
    } else if (navigator.userAgent.indexOf("Opera") != -1) {
        window.location = txt;
    } else if (window.netscape) {
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } catch (e) {
            alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");
        }
        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
        if (!clip)
            return;
        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
        if (!trans)
            return;
        trans.addDataFlavor('text/unicode');
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        var copytext = txt;
        str.data = copytext;
        trans.setTransferData("text/unicode", str, copytext.length * 2);
        var clipid = Components.interfaces.nsIClipboard;
        if (!clip)
            return false;
        clip.setData(trans, null, clipid.kGlobalClipboard);
    }
};

/**
 * 匿名方法 实例化全局对象
 */
(function(){
	if (typeof DcGlobal == "undefined" || !DcGlobal) {
		DcGlobal = new Global();
	} else{
		DcGlobal.log("DcGlobal is re-defined");
	}
})();